﻿using System;
using UnityEngine;
using Random = UnityEngine.Random;


public class TargetPoint : MonoBehaviour
{
    private const int EnemyLayerMask = 1 << 9;
    private static readonly Collider[] Buffer = new Collider[100];

    public Vector3 Position => transform.position;
    public Enemy Enemy { get; set; }
    public static int BufferedCount { get; set; }
    public static TargetPoint RandomBuffered => GetBuffered(Random.Range(0, BufferedCount));
    private void Awake()
    {
        Enemy = transform.root.GetComponent<Enemy>();
        Debug.Assert(Enemy != null, "Target point without Enemy root!", this);
        Debug.Assert(GetComponent<SphereCollider>() != null, "Target point without sphere collider!",this);
        Debug.Assert(gameObject.layer == 9, "Target point on wrong layer!", this);
        Enemy.TargetPointCollider = GetComponent<Collider>();
    }

    public static bool FillBuffer(Vector3 position, float range)
    {
        Vector3 top = position;
        top.y += 3f;
        BufferedCount = Physics.OverlapCapsuleNonAlloc(position, top, range, Buffer, EnemyLayerMask);
        return BufferedCount > 0;
    }

    public static TargetPoint GetBuffered(int index)
    {
        var target = Buffer[index].GetComponent<TargetPoint>();
        // Debug.Assert(target != null, "Targeted non-enemy!", buffer[0]);
        return target;
    }
}